<template>
  <div>
    <h3>user</h3>
    <!-- 面包导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="#">活动管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>活动列表 </el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card>
      <!-- 卡片视图里面的搜索 -->
      <el-row :gutter="20">
        <el-col :span="12"
          ><el-input
            placeholder="请输入内容"
            v-model="queryinfo.query"
            @clear="getUserList"
            clearable
          >
            <el-button
              @click="getUserList"
              slot="append"
              icon="el-icon-search"
            ></el-button> </el-input
        ></el-col>
        <!-- 添加用户 -->
        <el-col span="4">
          <el-button type="primary" @click="addDialogVisible = 'true'"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 卡片视图里面的用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column label="#" type="index"> </el-table-column>
        <el-table-column label="姓名" prop="username"> </el-table-column>
        <el-table-column label="邮箱" prop="email"> </el-table-column>
        <el-table-column label="电话" prop="mobile"> </el-table-column>
        <el-table-column label="角色" prop="role_name"> </el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <!-- 因为不能直接拿到当前行的数据 所有用v-slot scope.row来获取 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                @click="showSetRoleDialogVisable(scope.row)"
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 卡片视图里面分页设置 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[1, 2, 4, 10]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户弹出的对话框 -->
    <el-dialog
      title="添加用户"
      @close="closeForm"
      :visible.sync="addDialogVisible"
      width="50%"
    >
      <!-- 对话框主体 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部 取消 确认  -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogClosed"
    >
      <!-- 主体 -->
      <el-form
        :model="editFrom"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisable"
      width="50%"
    >
      <!-- 分配权限对话框中间部分 -->
      <div>
        <p>当前用户：{{ userinfo.username }}</p>
        <p>当前角色：{{ userinfo.role_name }}</p>
        <p>
          分配角色：
          <el-select v-model="selectedroleid" placeholder="请选择">
            <el-option
              v-for="item in rolelist"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <!-- 底部 -->
        <el-button @click="setRoleDialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="saveroleinfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>



<script>
export default {
  data() {
    //验证邮箱的校验规则 正则
    var checkEmail = (rule, value, callback) => {
      //验证邮箱的正则
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (regEmail.test(value)) {
        return callback();
      }
      callback("请输入合法的邮箱啊");
    };
    //验证手机号的校验规则 正则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1(3|4|5|7|8)\d{9}$/;
      console.log(value);

      if (regMobile.test(value)) {
        return callback();
      }
      callback("请你好好打手机号啊，！我写代码很辛苦的啊");
    };

    return {
      //获取用户列表的参数对象
      queryinfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      //用户列表
      userlist: [],
      total: 0,
      //添加用户对话框
      addDialogVisible: false,
      //添加用户的信息
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //添加用户的验证规则
      addFormRules: {
        username: [
          { required: true, message: "请输入您老的名字", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入您老的密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [{ required: true }, { validator: checkEmail, trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入您老的手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      //修改用户信息 校验规则 一直有问题 所以不加校验了 icantdoit
      editFormRules: {
        email: [
          // { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          // { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          // { required: true, message: '请输入用户手机', trigger: 'blur' },
          // { validator: checkMobile, trigger: 'blur' }
        ],
      },
      //修改用户对话框
      editDialogVisible: false,
      // 查询到的用户信息
      editForm: {
        username: "",
        email: "",
        mobile: "",
      },
      //显示添加权限的flag
      setRoleDialogVisable: false,
      //需要被分配角色的用户信息
      userinfo: {},
      //角色列表信息
      rolelist: [],
      //分配角色时候被选中 角色的id
      selectedroleid: "",
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryinfo,
      });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.errso("获取用户列表失败咯");
      }
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    //监听 每一页显示多少条 的函数 pagesize
    handleSizeChange(newsize) {
      console.log(newsize);
      this.queryinfo.pagesize = newsize;
      this.getUserList();
    },
    //监听当前页面变化的数据 pagenum
    handleCurrentChange(newpage) {
      console.log(newpage);
      this.queryinfo.pagenum = newpage;
      this.getUserList();
    },
    //监听每一个用户状态改变
    async userStateChanged(userinfo) {
      console.log(userinfo.mg_state);
      const { data: res } = await this.$http.put(`users/${userinfo.id}
      /state/${userinfo.mg_state}`);
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("更新用户状态失败了");
      }
      this.$message.success("更新用户状态成功了");
    },
    //关闭添加用户对话框以后充值表单
    closeForm() {
      this.$refs.addFormRef.resetFields();
    },
    //添加用户表单里点完确定 添加用户 操作
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请输入正确的信息！生气");
        const { data: res } = await this.$http.post("users", this.addForm);
        if (res.meta.status !== 201) return this.$message.error("添加失败");
        this.$message.success("添加用户成功啦");
        this.$refs.addFormRef.resetFields();
        this.addDialogVisible = false;
        this.getUserList();
      });
    },
    //打开修改用户对话框
    async showEditDialog(id) {
      // console.log( id );
      const { data: res } = await this.$http.get(`users/` + id);
      console.log(res);
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    //监听用户关闭修改框
    editDialogClosed() {
      this.editDialogVisible = false;
      this.$refs.editFormRef.resetFields();
    },
    //发送修改的请求 没有表单验证 icantdoit
    async editUserInfo() {
      const { data: res } = await this.$http.put("users/" + this.editForm.id, {
        email: this.editForm.email,
        mobile: this.editForm.mobile,
      });

      if (res.meta.status !== 200) return this.$message.error("提交修改失败");
      this.$message.success("提交修改成功");
      this.getUserList();
      this.editDialogVisible = false;
    },
    //删除该行user
    async removeUserById(id) {
      const confirmRseult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmRseult !== "confirm") {
        return this.$message.info("取消了删除");
      }
      const { data: res } = await this.$http.delete("users/" + id);
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error("删除失败");
      this.$message.success("删除成功了");
      this.getUserList();
    },

    //显示分配角色对话框
    async showSetRoleDialogVisable(role) {
      // console.log(role);
      this.userinfo = role;

      //显示角色列表
      const { data: res } = await this.$http.get("roles");
      // console.log(res.data);
      this.rolelist = res.data;
      console.log(this.rolelist);

      this.setRoleDialogVisable = true;
    },
    //提交 角色分配
    async saveroleinfo() {
      if (!this.selectedroleid) {
        return this.$message.error("请分配角色呀");
      }
      console.log(this.userinfo.id + "------" + this.selectedroleid);

      const { data: res } = await this.$http.put(
        `users/${this.userinfo.id}/role`,
        {
          rid: this.selectedroleid,
        }
      )
      console.log(res);

      if (res.meta.status !== 200)
        return this.$message.error("分配角色失败失败");
      this.$message.success("分配角色成功了");
      this.getUserList();
      this.setRoleDialogVisable = false;
    },
    setRoleDialogClosed() {
      this.selectedroleid = ''
      this.userinfo = {}
    },
  },
};
</script>

<style lang="less" scoped></style>
